#!/usr/bin/env bash

opal_install()
{
  rvm_log "Running Opal prereqs checking script."

  __rvm_which node > /dev/null &&
  __rvm_which npm  > /dev/null ||
  {
    result=$?
    rvm_error "Prerequisite checks have failed - can not find 'node' and/or 'npm' commands.
Halting the installation."
    return $result
  }

  __rvm_log_command "prepare_directories" \
    "Preparing directories for opal" \
    opal_install_prepare_directories

  __rvm_cd "${rvm_ruby_home}"

  system="${_system_type}"
  arch="$(file "$( __rvm_which node)" )"
  arch="$(echo "${arch##* }" )"

  if
    node_binary="$(
      __rvm_which opal-node 2>/dev/null ||
      npm explore opal -- which bin/opal-node 2>/dev/null
    )"
  then
    rvm_log "Found opal-node at $node_binary"
  else
    __rvm_log_command "npm.install.opal" \
      "Installing opal-node" \
      npm install opal ||
      return $result

    node_binary="$(
      npm explore opal -- which bin/opal-node 2>/dev/null
    )"
  fi

  __rvm_log_command "install" \
    "Installing opal to $rvm_ruby_home" \
    opal_install_files
}

opal_install_prepare_directories()
{
  __rvm_rm_rf "$rvm_ruby_home" &&
  \command \mkdir -vp "${rvm_ruby_home}/bin/" &&
  \command \mkdir -vp "$rvm_ruby_gem_home/bin" &&
  \command \mkdir -vp "$rvm_ruby_global_gems_path/bin" ||
  return $?
}

opal_install_files()
{
  __rvm_cd "$rvm_ruby_home/bin/"

  ln -fs "$node_binary" "ruby"

  cat <<-FAKE_GEM > gem
#!/usr/bin/env bash

echo "OPAL FAKE GEM COMMAND: $@"
exit 127
FAKE_GEM

  chmod +x ruby gem

  cat <<-FAKE_CONFIG > "$rvm_ruby_home/config"
target_cpu=$arch
FAKE_CONFIG
}
